const express = require('express');
const punch = express.Router();
const query = require('../../sql/config');
punch.get('/getList', async (req, res) => {
  let { name, pageNum, pageSize } = req.query;
  pageNum = pageNum || 1;
  pageSize = pageSize || 10;
  const searchName = name ? `punch.name like '%${name}%' and ` : '';
  const originalList = await query(`select punch.id,punch.name,punch.createTime,user.name author from punch,user where ${searchName}punch.status = 0 order by punch.createTime desc`);
  const middleList = originalList.map(async punch => {
    const { editor, lastEditTime } = (await query(`select po.createTime as lastEditTime,user.name as editor from punch_operator as po,user where punchId = '${punch.id}' order by po.createTime desc limit 1`))[0];
    punch.editor = editor;
    punch.lastEditTime = lastEditTime;
    return punch;
  });
  Promise.all(middleList)
  .then(punchList => {
    res.json({
      code: 200,
      msg: '查询成功',
      total: punchList.length,
      pageNum: Number(pageNum),
      pageSize: Number(pageSize),
      rows: punchList.slice((pageNum - 1) * pageSize, pageNum * pageSize)
    });
  })
  .catch(err => {
    res.json({
      code: 404,
      msg: '查询失败',
      total: 0,
      pageNum: Number(pageNum),
      pageSize: Number(pageSize),
      rows: []
    });
  });
});
module.exports = punch;
